package com.wc.data_structures.queue;

import java.util.Arrays;

/**
 * @Author congge
 * @Date 2023/4/18 18:07
 * @description
 */
public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        CircleArrayQueue<Integer> circleArrayQueue = new CircleArrayQueue<>(10);

        circleArrayQueue.showQueue();
    }
}

class CircleArrayQueue<T> {
    // 最大容量
    private final int maxSize;
    // 队头
    private int front;
    // 队尾
    private int rear;
    // 数组用存放数据
    private final T[] array;

    // 初始化队列
    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        array = (T[]) new Object[maxSize];
        // 指向队列头部，分析出front指向队列头
        front = 0;
        // 指向队列尾部的后一个元素，
        rear = 0;
    }


    // 判断队列是否是满的
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    // 判断队列是否为空
    public boolean isEmpty() {
        return rear == front;
    }

    // 添加数据到队列
    public void addQueue(T num) {
        // 判断是否为满
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }

        array[rear] = num;
        rear = (rear + 1) % maxSize;
    }

    // 出队列
    public T getQueue() {
        // 判断是否为空
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        T value = array[front];
        front = (front + 1) % maxSize;

        return value;
    }

    // 获得队头
    public T peekQueue() {
        // 判断是否为空
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return array[front];
    }

    // 展示队列
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("数列为空");
            return;
        }
        for (int i = front; i < front + size(); i++) {
            System.out.print(array[i % maxSize] + "\t");
        }
        System.out.println();
    }

    //  记录队列中有多少个数
    public int size() {
        return (rear - front + maxSize) % maxSize;
    }
}